package org.example.config;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class MyPreAndPostGatewayFilterFactory extends
        AbstractGatewayFilterFactory<MyPreAndPostGatewayFilterFactory.Config> {

    public MyPreAndPostGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return super.shortcutFieldOrder();
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // 在路由请求前向请求头中添加名称为x-request-id的信息
            ServerHttpRequest request = exchange.getRequest();
            request.mutate().header("x-request-id", "request-abc");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                // 在路由响应后向响应头中添加名称为x-response-id的信息
                ServerHttpResponse response = exchange.getResponse();
                response.beforeCommit(() -> {
                    response.getHeaders().add("x-response-id", "response-abc");
                    return Mono.empty();
                });
            }));
        };
    }
    /** 添加配置项 */
    public static class Config {
    }
}